#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
查询采集到的提问 - 演示脚本
"""

import requests
import json
import time
from datetime import datetime

API_BASE = "http://localhost:5000/api"

def check_service_status():
    """检查服务状态"""
    try:
        response = requests.get(f"{API_BASE}/status")
        if response.status_code == 200:
            status = response.json()
            print("🟢 服务运行正常")
            print(f"📊 监听状态: {'监听中' if status['is_monitoring'] else '未监听'}")
            print(f"📝 队列问题数: {status['queue_size']}")
            if status.get('room_info'):
                print(f"🏠 直播间: {status['room_info']['title']}")
                print(f"🆔 房间ID: {status['room_info']['room_id']}")
            return True
        else:
            print("🔴 服务状态异常")
            return False
    except Exception as e:
        print(f"🔴 无法连接到服务: {e}")
        return False

def get_questions():
    """获取问题列表"""
    try:
        response = requests.get(f"{API_BASE}/questions")
        if response.status_code == 200:
            data = response.json()
            questions = data.get('questions', [])
            total = data.get('total', 0)
            
            print(f"\n📋 采集到的问题列表 (共 {total} 个):")
            print("=" * 60)
            
            if questions:
                for i, question in enumerate(questions, 1):
                    print(f"{i}. 【{question['user']}】 {question['timestamp']}")
                    print(f"   问题: {question['question']}")
                    print(f"   房间: {question['room_id']}")
                    print("-" * 40)
            else:
                print("暂无问题")
                print("💡 提示: 确保已开始监听直播间，并且有观众发送以'??'结尾的评论")
            
            return questions
        else:
            print(f"🔴 获取问题失败: HTTP {response.status_code}")
            return []
    except Exception as e:
        print(f"🔴 获取问题失败: {e}")
        return []

def start_monitoring_demo():
    """启动监听演示"""
    print("🚀 启动监听演示...")
    
    # 检查当前配置
    try:
        response = requests.get(f"{API_BASE}/room-url")
        if response.status_code == 200:
            config = response.json()
            room_url = config.get('room_url', '')
            room_id = config.get('room_id', '')
            
            if room_url or room_id:
                print(f"📡 当前配置的直播间: {room_url or room_id}")
                
                # 开始监听
                start_response = requests.post(f"{API_BASE}/start", json={
                    "room_id": room_url or room_id
                })
                
                if start_response.status_code == 200:
                    result = start_response.json()
                    if result.get('success'):
                        print("✅ 监听已启动")
                        return True
                    else:
                        print(f"❌ 启动失败: {result.get('message')}")
                else:
                    print(f"❌ 启动失败: HTTP {start_response.status_code}")
            else:
                print("❌ 未配置直播间URL")
                print("💡 请先通过Web界面或API配置直播间URL")
    except Exception as e:
        print(f"❌ 启动失败: {e}")
    
    return False

def monitor_questions_realtime():
    """实时监控问题"""
    print("\n🔄 开始实时监控问题...")
    print("按 Ctrl+C 停止监控")
    
    try:
        while True:
            questions = get_questions()
            
            # 等待10秒后再次查询
            print(f"\n⏰ {datetime.now().strftime('%H:%M:%S')} - 等待10秒后刷新...")
            time.sleep(10)
            
    except KeyboardInterrupt:
        print("\n👋 监控已停止")

def main():
    """主函数"""
    print("=" * 60)
    print("🎯 直播间问题采集工具 - 查询演示")
    print("=" * 60)
    
    # 1. 检查服务状态
    if not check_service_status():
        print("\n💡 请先启动服务:")
        print("   python app.py")
        return
    
    # 2. 获取当前问题
    questions = get_questions()
    
    # 3. 如果没有问题，提供启动监听的选项
    if not questions:
        print("\n🤔 没有采集到问题，可能原因:")
        print("1. 还未开始监听直播间")
        print("2. 直播间暂时没有观众提问")
        print("3. 观众的评论没有以'??'结尾")
        
        choice = input("\n是否启动监听? (y/n): ").lower()
        if choice == 'y':
            if start_monitoring_demo():
                monitor_questions_realtime()
    else:
        # 4. 如果有问题，询问是否实时监控
        choice = input("\n是否开始实时监控? (y/n): ").lower()
        if choice == 'y':
            monitor_questions_realtime()

if __name__ == "__main__":
    main()